package com.tanhua.manage.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.manage.domain.Admin;
import com.tanhua.manage.exception.BusinessException;
import com.tanhua.manage.mapper.AdminMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jdk.nashorn.internal.parser.Token;
import jdk.nashorn.internal.parser.TokenKind;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService extends ServiceImpl<AdminMapper, Admin> {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Value("${tanhua.secret}")
    private String secret;

    /**
     * 保存验证码到redis中
     */
    public void saveCap(String uuid, String code) {
        redisTemplate.opsForValue().set("MANAGE_CAP_"+uuid,code, Duration.ofMinutes(2));
    }

    /**
     * 登陆
     */
    public ResponseEntity<Object> login(Map<String, String> map) {
        //1. 获取请求参数
        String username = map.get("username");
        String password = map.get("password");
        String verificationCode = map.get("verificationCode");
        String uuid = map.get("uuid");

        //2. 校验验证码
        //2.1 从redis中获取验证码
        String code = redisTemplate.opsForValue().get("MANAGE_CAP_" + uuid);
        if (StringUtils.isEmpty(code) || !verificationCode.equals(code)) {
            // 返回异常
            throw new BusinessException("验证码校验失败！");
        }

        // 删除验证码
        redisTemplate.delete("MANAGE_CAP_" + uuid);

        //3. 登陆校验
        //3.1 根据用户名查询
        Admin admin = query().eq("username", username).one();
        if (admin == null) {
            // 账号不存在
            throw new BusinessException("用户名输入错误！");
        }
        //3.2 校验密码
        if (!SecureUtil.md5(password).equals(admin.getPassword())) {
            // 密码错误
            throw new BusinessException("密码输入错误!");
        }

        //4. 生成token、返回
        //4.1 准备生成token加密的数据
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put("id",admin.getId());
        tokenMap.put("username",admin.getUsername());
        //4.2 生成token
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, secret)
                .setClaims(tokenMap).compact();
        //4.3 把生成的token存储到redis中
        //4.3.1 对象转json
        String jsonString = JSON.toJSONString(admin);
        //4.3.2 存入到redis中
        redisTemplate.opsForValue().set("MANAGE_TOKEN_"+ token,jsonString,Duration.ofHours(4));

        //4.4 返回token
        Map<String,String> result = new HashMap<>();
        result.put("token",token);
        return ResponseEntity.ok(result);
    }

    /**
     * 解析token获取用户
     * @param token
     * @return
     */
    public Admin findUserByToken(String token) {
        String adminJsonString = redisTemplate.opsForValue().get("MANAGE_TOKEN_" + token);
        return JSON.parseObject(adminJsonString,Admin.class);
    }

    public ResponseEntity<Object> logout(String token) {
        redisTemplate.delete("MANAGE_TOKEN_"+token);
        return ResponseEntity.ok(null);
    }
}
